<?php
	class Banner extends LiladsAppModel {
		var $name = 'Banner';
		var $useTable = 'lilads_banners';
		var $validate = array(
			'title' => array('rule'=>array('minLength', '1'), 'required'=>true),
			'link' => array('rule'=>'url', 'allowEmpty'=>true),
			'kind' => array('format' => array('rule' => array('custom', '/^(I|H|P|F)$/'))),
			'width' => array('rule'=>'numeric', 'allowEmpty'=>true),
			'height' => array('rule'=>'numeric', 'allowEmpty'=>true),
		);

		var $actsAs = array(
			'Lilads.Upload'=>array(
				'fileField' => 'filename',
				'allowedExt' => array('gif', 'jpg', 'png', 'swf'),
				'overwriteExisting' => false,
				'baseDir' => '{APP}webroot{DS}img{DS}ads{DS}',
				'fileFormat' => '{$filename}',
				'dirFormat' => '.',
		));
		
		function __construct($id = false, $table = null, $ds = null) {		
			$this->actsAs['Lilads.Upload']['baseDir'] = Configure::read('Lilads.uploadFolder');
			parent::__construct($id, $table, $ds);
		}

		function findForLocation($location_id=null) {
			App::import('Model', 'Lilads.Location');
			$location = new Location();
			if (is_numeric($location_id) && $location_data = $location->read(null, $location_id)) {
				$conditions = array();
				$conditions['Campaign.active'] = 1;
				
				$conditions['Banner.kind'] = array();
				if (!empty($location_data['Location']['accept_image'])) $conditions['Banner.kind'][] = 'I';
				if (!empty($location_data['Location']['accept_flash'])) $conditions['Banner.kind'][] = 'F';
				if (!empty($location_data['Location']['accept_html']))  $conditions['Banner.kind'][] = 'H';
				if (!empty($location_data['Location']['accept_plain'])) $conditions['Banner.kind'][] = 'P';
				if (empty($conditions['Banner.kind'])) unset($conditions['Banner.kind']);
				
				if (!empty($location_data['Location']['width'])) $conditions['Banner.width'] = $location_data['Location']['width'];
				if (!empty($location_data['Location']['height'])) $conditions['Banner.height'] = $location_data['Location']['height'];
				
				$conditions[] = array('OR'=>array(0=>array('Campaign.limit_start'=>null), 1=>array('Campaign.limit_start <='=>strftime('%Y-%m-%d'))));
				$conditions[] = array('OR'=>array(0=>array('Campaign.limit_end'=>null), 1=>array('Campaign.limit_end >='=>strftime('%Y-%m-%d'))));
				$conditions[] = array('OR'=>array(0=>array('Campaign.limit_views'=>null), 1=>array('Campaign.views <='=>'Campaign.limit_views')));
				$conditions[] = array('OR'=>array(0=>array('Campaign.limit_clicks'=>null), 1=>array('Campaign.clicks <='=>'Campaign.limit_clicks')));
				
				App::import('Model', array('Lilads.Campaign', 'Lilads.Action'));
				$action = new Action();
				$this->bindModel(array('belongsTo'=>array('Campaign')));
				if ($banner = $this->find('first', array('conditions'=>$conditions, 'order'=>'(4-Campaign.priority)*RAND() DESC'))) {
					$banner['Location'] = $location_data['Location'];
					$db =& ConnectionManager::getDataSource($this->useDbConfig);
					$db->execute("UPDATE ".$this->Campaign->table." SET views=views+1 WHERE id=".$banner['Campaign']['id']);
					$db->execute("UPDATE ".$action->table." SET views=views+1 WHERE campaign_id=".$banner['Campaign']['id']." AND banner_id=".$banner['Banner']['id']." AND date_hour='".strftime('%Y-%m-%d %H:00:00')."'");
					if (!$db->affected) {
						$db->execute("INSERT INTO ".$action->table." (campaign_id, banner_id, date_hour, views) VALUES (".$banner['Campaign']['id'].",".$banner['Banner']['id'].",'".strftime('%Y-%m-%d %H:00:00')."',1)");
					}
					return $banner;
				}
			}
			return false;
		}

		function click($id=null) {
			if (is_numeric($id) && $banner = $this->read(null, $id)) {
				App::import('Model', array('Lilads.Campaign', 'Lilads.Action'));
				$action = new Action();
				$campaign = new Campaign();
				$campaign->query("UPDATE ".$campaign->table." SET clicks=clicks+1 WHERE id=".$banner['Banner']['campaign_id']);
				
				$db =& ConnectionManager::getDataSource($this->useDbConfig);
				$db->execute("UPDATE ".$action->table." SET clicks=clicks+1 WHERE campaign_id=".$banner['Banner']['campaign_id']." AND banner_id=".$banner['Banner']['id']." AND date_hour='".strftime('%Y-%m-%d %H:00:00')."'");
				if (!$db->affected) {
					$db->execute("INSERT INTO ".$action->table." (campaign_id, banner_id, date_hour, clicks) VALUES (".$banner['Banner']['campaign_id'].",".$banner['Banner']['id'].",'".strftime('%Y-%m-%d %H:00:00')."',1)");
				}
				return $banner['Banner']['link'];
			}
			return false;
		}
	}
?>